package com.ruoyi.central.controller;

import java.io.*;
import java.util.List;

import com.ruoyi.central.controller.vo.TaskCmdRunVo;
import com.ruoyi.central.domain.*;
import com.ruoyi.central.exception.task.cmd.run.TaskCmdRunException;
import com.ruoyi.central.service.*;
import com.ruoyi.central.utils.pojo.TaskCmdRunUtils;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.interfaces.imple.DynamicTemplateImpl;
import com.ruoyi.common.exception.base.data.DataValidationException;
import com.ruoyi.common.exception.base.domian.EntityNotFoundOrDisableException;
import com.ruoyi.common.exception.base.service.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.validation.group.InsertGroup;
import com.ruoyi.common.validation.group.UpdateGroup;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.utils.bean.SelectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.validation.group.UpdateBatchGroup;
import com.ruoyi.common.core.domain.StateVo;
import java.util.Collection;

/**
 * 任务执行指令Controller
 * 
 * @author SunLuQuan
 * @date 2022-05-29
 */
@Controller
@RequestMapping("/central/centralTaskCmdRun")
public class TopCentralTaskCmdRunController extends BaseController
{
    private String prefix = "central/centralTaskCmdRun";

    @Autowired
    private ITopCentralTaskCmdRunService topCentralTaskCmdRunService;

    @Autowired
    private ITopCentralTaskCmdService taskCmdService;

    @Autowired
    private ITopCentralProcessStepRunService processStepRunService;

    @Autowired
    private ITopCentralArtProcessRunService artProcessRunService;

    @Autowired
    private ITopCentralMaterialService materialService;

    @RequiresPermissions("central:centralTaskCmdRun:view")
    @GetMapping()
    public String centralTaskCmdRun()
    {
        return prefix + "/centralTaskCmdRun";
    }

    /**
     * 根据任务指令执行编号 找到 需要调用的模板对象
     * @param params
     * @param mmap
     * @return
     */
    @GetMapping("/toTaskCmdRunTemplate")
    public String toTaskCmdRunTemplate(@Validated TaskCmdRunVo.Params params, ModelMap mmap) throws IOException {

        Integer processStepRunId = params.getProcessStepRunId();
        Integer taskCmdRunId = params.getTaskCmdRunId();
        Integer artProcessRunId;
        String materialId ;
        TopCentralTaskCmd taskCmd;
        TopCentralTaskCmdRun activeTaskCmdRun;
        TopCentralProcessStepRun activeProcessStepRun;
        TopCentralArtProcessRun artProcessRun;
        TopCentralMaterial material;

        activeTaskCmdRun = topCentralTaskCmdRunService.getFinishedNextByProcessStepRunId(processStepRunId);

        taskCmd = taskCmdService.selectUsableById(activeTaskCmdRun.getTaskCmdId());

        activeTaskCmdRun.setTaskCmd(taskCmd);

        if(!StringUtils.equals(activeTaskCmdRun.getId(),taskCmdRunId)){

            throw new TaskCmdRunException.DataValidationException();
        }

        TaskCmdRunUtils.operationCheck(activeTaskCmdRun);

        activeProcessStepRun = processStepRunService.selectUsableById(processStepRunId);

        artProcessRunId = activeProcessStepRun.getArtProcessRunId();

        artProcessRun = artProcessRunService.selectUsableById(artProcessRunId);

        materialId = artProcessRun.getProdId();

        material = materialService.selectUsableById(materialId);


        String templatePath = new StringBuilder("centralTaskCmdRun").append(File.separator).append(taskCmdRunId.toString())
                .append("taskCmdRunTemplate.html").toString();
        String absolutePath = new StringBuilder(RuoYiConfig.getTemplatesPath())
                .append(File.separator).append(templatePath).toString();

        File fileOfTemplate = new File(absolutePath);

        if(!fileOfTemplate.exists()){
            DynamicTemplateImpl dynamicTemplateImpl = new DynamicTemplateImpl(taskCmd.getTemplate());
            File dynamicTemplateFile = dynamicTemplateImpl.getFillFile();

            org.apache.commons.io.FileUtils.copyFile(dynamicTemplateFile, fileOfTemplate);
//            FileUtils.copyFileByChannel(dynamicTemplateFile,fileOfTemplate);
        }

        mmap.put("taskCmdRun",activeTaskCmdRun);
        mmap.put("taskCmd",taskCmd);
        mmap.put("material",material);
        mmap.put("artProcessRun",artProcessRun);
        mmap.put("processStepRun",activeProcessStepRun);

        return "central/manualOperationStation/selectOperationStation";
    }

    /**
     * 查询任务执行指令列表
     */
    @RequiresPermissions("central:centralTaskCmdRun:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(TopCentralTaskCmdRun topCentralTaskCmdRun)
    {
        startPage();
        List<TopCentralTaskCmdRun> list = topCentralTaskCmdRunService.selectList(topCentralTaskCmdRun);
        return getDataTable(list);
    }

    /**
     * 查询简单的任务执行指令列表 用于select选择器
     */
    @GetMapping("/simpleList")
    @ResponseBody
    public AjaxResult simpleList(TopCentralTaskCmdRun topCentralTaskCmdRun){

        Collection<TopCentralTaskCmdRun> topCentralTaskCmdRunList = topCentralTaskCmdRunService.selectAllMap().values();

        return AjaxResult.success(SelectUtils.buildSelectList(topCentralTaskCmdRunList,TopCentralTaskCmdRun::getId,TopCentralTaskCmdRun::getTaskCmdId));
    }

    /**
     * 获取任务执行指令详细信息
     */
    @RequiresPermissions("central:centralTaskCmdRun:query")
    @GetMapping(value = "/{id}")
    @ResponseBody
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return AjaxResult.success(topCentralTaskCmdRunService.selectById(id));
    }

    /**
     * 获取自增排序值
     * @param topCentralTaskCmdRun 过滤条件
     * @return
     */
    @GetMapping("/getIncrementWeight")
    @ResponseBody
    public AjaxResult getIncrementWeight(TopCentralTaskCmdRun topCentralTaskCmdRun){
        int weigth = topCentralTaskCmdRunService.getMaxOfWeight(topCentralTaskCmdRun);
        return AjaxResult.success(++weigth);
    }

    /**
     * 下载任务执行指令导入模板
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<TopCentralTaskCmdRun> util = new ExcelUtil<>(TopCentralTaskCmdRun.class);
        util.importTemplateExcel(response, "任务执行指令数据");
    }

    /**
     * 导入任务执行指令数据
     * @param file 任务执行指令数据文件
     * @param updateSupport 是否为更新
     */
    @Log(title = "任务执行指令", businessType = BusinessType.IMPORT)
    @RequiresPermissions("central:centralTaskCmdRun:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TopCentralTaskCmdRun> util = new ExcelUtil<>(TopCentralTaskCmdRun.class);
        List<TopCentralTaskCmdRun> topCentralTaskCmdRunList = util.importExcel(file.getInputStream());

        if(updateSupport){
            if(topCentralTaskCmdRunService.updateBatchById(topCentralTaskCmdRunList)){
                return AjaxResult.success("导入任务执行指令数据覆盖成功！");
            }
            return AjaxResult.error("导入任务执行指令数据覆盖失败！");
        }
        if(topCentralTaskCmdRunService.insertBatch(topCentralTaskCmdRunList)){
            return AjaxResult.success("导入任务执行指令数据新增成功！");
        }
        return AjaxResult.error("导入任务执行指令数据新增失败！");
    }

    /**
     * 导出任务执行指令列表
     */
    @RequiresPermissions("central:centralTaskCmdRun:export")
    @Log(title = "任务执行指令", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TopCentralTaskCmdRun topCentralTaskCmdRun)
    {
        List<TopCentralTaskCmdRun> list = topCentralTaskCmdRunService.selectList(topCentralTaskCmdRun);
        ExcelUtil<TopCentralTaskCmdRun> util = new ExcelUtil<TopCentralTaskCmdRun>(TopCentralTaskCmdRun.class);
        return util.exportExcel(list, "任务执行指令数据");
    }

    /**
     * 新增任务执行指令
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存任务执行指令
     */
    @RequiresPermissions("central:centralTaskCmdRun:add")
    @Log(title = "任务执行指令", businessType = BusinessType.INSERT)
    @PostMapping
    @ResponseBody
    public AjaxResult addSave(@Validated(InsertGroup.class) @RequestBody TopCentralTaskCmdRun topCentralTaskCmdRun)
    {
        return toAjax(topCentralTaskCmdRunService.insert(topCentralTaskCmdRun));
    }

    /**
     * 修改任务执行指令
     */
    @RequiresPermissions("central:centralTaskCmdRun:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        TopCentralTaskCmdRun topCentralTaskCmdRun = topCentralTaskCmdRunService.selectById(id);
        mmap.put("topCentralTaskCmdRun", topCentralTaskCmdRun);
        return prefix + "/edit";
    }

    /**
     * 修改保存任务执行指令
     */
    @RequiresPermissions("central:centralTaskCmdRun:edit")
    @Log(title = "任务执行指令", businessType = BusinessType.UPDATE)
    @PutMapping
    @ResponseBody
    public AjaxResult editSave(@Validated(UpdateGroup.class) @RequestBody TopCentralTaskCmdRun topCentralTaskCmdRun)
    {
        return toAjax(topCentralTaskCmdRunService.updateById(topCentralTaskCmdRun));
    }

    /**
     * 修改任务执行指令 状态 根据 ids 主键
     */
    @RequiresPermissions("central:centralTaskCmdRun:edit")
    @Log(title = "任务执行指令", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStateByIds")
    @ResponseBody
    public AjaxResult updateStateByIds(@Validated(value= UpdateBatchGroup.class)@RequestBody StateVo<Integer> stateVo)
    {
        return toAjax(topCentralTaskCmdRunService.updateStateByIds(stateVo.getIds(),stateVo.getState()));
    }

    /**
     * 删除任务执行指令
     */
    @RequiresPermissions("central:centralTaskCmdRun:remove")
    @Log(title = "任务执行指令", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ResponseBody
    public AjaxResult deleteByIds(@PathVariable("ids") List<Integer> ids)
    {
            return toAjax(topCentralTaskCmdRunService.deleteByIds(ids));
    }
}
